<template>
  <div class="p-3" style="background-color: #eceff8">
    <SystemSelect :sub-system="subSystem" @selectChange="selectChange" />
    <div class="flex" :style="{ height: `${Number(getHeight)}px` }">
      <div class="h-full" style="width: 20%; padding: 10px 15px 0 0">
        <!-- <Forms ref="subForm" :auto-query="true" :data-from="formData" :list="searchForm" name="roleAuthorization" />
        <div style="display: flex">
          <el-button @click="newAdd">新增</el-button>
          <el-button @click="roleCopy">复制</el-button>
        </div>
        <Table
          :btn-fix="true"
          :column-list="tablesColumn"
          :get-height="`${Number(getHeight)}`"
          name="userAuthorization"
          :style="{ height: `${Number(getHeight)}px` }"
          :tables="tables"
        /> -->
        <div class="h-full" style="background-color: #fff">
          <div class="role-heder bg-gray-200">
            <div>
              <vui-icon icon="user-fill" style="color: #6492fd" />
              <span>{{ translateTitle('Dams.ApplicationInterface.角色名称') }}</span>
            </div>
            <div>
              <vui-icon class="cursor-pointer" icon="add-fill" @click="newAdd" />
            </div>
          </div>
          <div class="role-content">
            <div v-for="(v, i) in tables.tableList" :key="i" class="role-item" @click="clickOne(v)">
              <div>
                <vui-icon icon="user-line" style="color: #6492fd" />
                <span>{{ v.ROLE_NAME }}</span>
              </div>
              <div class="role-item-btn">
                <vui-icon class="cursor-pointer" icon="pencil-line" style="color: #6492fd" @click.stop="editClick(v)" />
                <vui-icon class="cursor-pointer" icon="file-copy-line" style="color: #6492fd" @click.stop="roleCopy(v)" />
                <vui-icon class="cursor-pointer" icon="delete-bin-line" style="color: #6492fd" @click.stop="deleteRole(v)" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="relative h-full" style="width: 80%; padding-top: 10px">
        <el-tabs class="h-full" type="border-card" @tab-click="firstTab">
          <el-tab-pane class="p-3 flex" :label="translateTitle('Dams.ApplicationInterface.菜单按钮权限')">
            <div v-if="menuTreeDataList.length == 0" style="display: flex; justify-content: center; width: 100%">
              <el-empty :description="translateTitle('Dams.ApplicationInterface.暂无数据请选中角色进行配置')" />
            </div>
            <el-tabs v-else v-model="activeName" class="w-full" @tab-click="handleClick">
              <el-tab-pane
                v-for="(item, i) in menuTreeDataList"
                :key="i"
                :label="`${item.name + translateTitle('Dams.ApplicationInterface.菜单')}`"
                :name="item.name"
              >
                <div class="flex">
                  <div class="w-1/2 border-solid border p-3">
                    <div class="w-full p-3 relative" style="background-color: #f5f7fa">
                      <p class="text-center font-bold">{{ translateTitle('Dams.ApplicationInterface.菜单') }}</p>
                      <div class="absolute" style="top: 10px; right: 10px">
                        <el-button style="padding: 0; margin: 0" type="text" @click="unFoldAll2(item.treeDataList)">
                          {{ translateTitle('Dams.ApplicationInterface.展开') }}
                        </el-button>
                        /
                        <el-button style="padding: 0; margin: 0" type="text" @click="collapseAll2(item.treeDataList)">
                          {{ translateTitle('Dams.ApplicationInterface.折叠') }}
                        </el-button>
                      </div>
                    </div>
                    <div class="overflow-y-auto" :style="{ height: Number(getHeight) - 200 + 'px' }">
                      <el-tree
                        :ref="`tree_menu_${item.name}`"
                        :data="item.treeDataList"
                        :default-checked-keys="item.secondListPC"
                        node-key="id"
                        :props="defaultProps"
                        :show-checkbox="true"
                        @check="checkedChange"
                        @node-click="nodePcClick"
                      />
                    </div>
                    <div class="text-center">
                      <el-button v-if="item.treeDataList && item.treeDataList.length != 0" type="primary" @click="save('main')">
                        {{ translateTitle('Dams.ApplicationInterface.保存') }}
                      </el-button>
                    </div>
                  </div>
                  <div v-loading="loadingCheckbox" class="w-1/2 border-solid border p-3 ml-2.5">
                    <div class="w-full p-3 text-center font-bold" style="background-color: #f5f7fa">
                      {{ translateTitle('Dams.ApplicationInterface.业务按钮字段') }}
                    </div>
                    <div v-if="buttonList.length != 0" class="grid-content bg-purple">
                      <div class="overflow-y-auto" :style="{ height: Number(getHeight) - 200 + 'px' }">
                        <el-tree
                          v-if="buttonList.length > 0"
                          :ref="`tree_btn_${item.name}`"
                          :data="buttonList"
                          :default-checked-keys="defaultExpandedKeys"
                          default-expand-all
                          node-key="id"
                          :props="defaultProps"
                          :check-strictly="true"
                          show-checkbox
                          @check="checkChange"
                        />
                      </div>
                      <div class="text-center">
                        <el-button type="primary" @click="save('chirden')">{{ translateTitle('Dams.ApplicationInterface.保存') }}</el-button>
                      </div>
                    </div>
                    <div v-else style="display: flex; justify-content: center; width: 100%">
                      <el-empty :description="translateTitle('Dams.ApplicationInterface.暂无数据请选中菜单进行配置')" />
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
          <el-tab-pane :disabled="menuTreeDataList.length == 0" :label="translateTitle('Dams.ApplicationInterface.绑定的用户')">
            <Table
              :btn-fix="false"
              :column-list="userTablesColumn"
              :get-height="`${Number(getHeight) - 100}`"
              name="userBind"
              :style="{ height: `${Number(getHeight) - 100}px` }"
              :tables="userTables"
            />
            <div class="text-center">
              <el-button size="small" type="primary" @click="roleUserBind">{{ translateTitle('Dams.ApplicationInterface.编辑') }}</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <el-dialog
      v-model="addDialog"
      :close-on-click-modal="false"
      :title="dialogType == 'add' ? translateTitle('Dams.ApplicationInterface.新增') : translateTitle('Dams.ApplicationInterface.编辑')"
      width="80%"
    >
      <Forms
        v-if="addDialog"
        :data-from="formDialog"
        label-position="top"
        :list="pageSetting[moduleName].dialog"
        name="MenuButtonPulic"
        :type="dialogType"
      />
    </el-dialog>
    <VuiModal v-if="userDialog" v-model="userDialog">
      <template #title>{{ translateTitle('Dams.ApplicationInterface.用户信息') }}</template>
      <el-transfer
        v-model="associatedTables"
        :data="notAssociatedTables"
        filterable
        :props="{
          key: 'USER_ID',
          label: 'USER_NAME',
        }"
        :titles="[translateTitle('Dams.ApplicationInterface.绑定未关联用户'), translateTitle('Dams.ApplicationInterface.已关联')]"
      />

      <template #footer>
        <div class="flex justify-center p-3 border-t border-gray-100">
          <el-button size="small" type="primary" @click="roleBindUserSave">{{ translateTitle('Dams.ApplicationInterface.保存') }}</el-button>
        </div>
      </template>
    </VuiModal>
    <Download
      v-if="Object.keys(pageSetting).length > 0 && downloadModal"
      :checkboxlist="checkboxList"
      :download-methods="pageSetting.downloadMethod"
      :is-modal="downloadModal"
      :search-form="subForm"
      :search-table-methods="pageSetting.search.form.method"
      :sub-system="tables.subsystem"
      :table-column="tablesColumn"
      :tablelist="tables.tableList"
      @close="downloadClose"
    />
    <Upload
      v-if="uploadModal"
      :export-form="exportForm"
      :is-modal="uploadModal"
      :template-method="tables.templateMethod"
      :upload-options="uploadOptions"
      @closeUpload="closeUpload"
    />
  </div>
</template>

<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import { arrayToTree } from '@/utils/tools'
  // import publicPageVue from './publicPage.vue'
  import { getList } from '../api/home'
  // import getTree from '../../components/tree.vue'
  import Table from './table.vue'
  import Download from './download'
  import Upload from './upload'
  import debounce from 'lodash/debounce'
  import Forms from './forms'
  import SystemSelect from './systemSelect'
  import { getComponents } from '@/ve/utils/extendData'
  import cloneDeep from 'lodash/cloneDeep'
  import { translateTitle } from '@/utils/i18n'
  import { ungzip } from '@/utils/gzip.js'
  export default {
    name: 'MenuButtonPulic',
    components: {
      // publicPageVue,
      // getTree,
      Table,
      Forms,
      Download,
      Upload,
      SystemSelect,
    },
    mixins: [Mixin],
    props: {
      moduleName: {
        type: String,
        default: '',
      },
      pageSetting: {
        type: Object,
        default: () => {},
      },
    },
    data() {
      return {
        exportForm: {
          SUB_SYSTEM: 'WMS',
          TABLE_NAME: 'PRI_ROLE',
        },
        uploadOptions: {
          postData: {
            method: 'wms.role.import',
          },
          name: 'uploadFile',
          url: ``,
        },
        formDialog: {},
        subForm: {},
        tableOtherList: [],
        clientHeight: 0,
        loadingTree: false,
        loadingCheckbox: false,
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        treeData: [],
        activeName: 'PC',
        tables: {
          tableList: [],
          count: 0,
          pageSize: 50,
          limit: 1,
          name: 'MenuButtonPulic',
          operation: true, //true双击显示右侧不显示操作按钮
          myselfOperation: true, //自己单独的双击事件
          isNew: false,
          width: '100',
          autoQuery: true, //第一次自动查询
        },
        notAssociatedTables: [],
        associatedTables: [],
        userTables: {
          tableList: [],
          count: 0,
          pageSize: 50,
          limit: 1,
          name: 'MenuButtonPulicUser',
          operation: true, //true双击显示右侧不显示操作按钮
          myselfOperation: true, //自己单独的双击事件
          isNew: false,
          width: '100',
          autoQuery: true, //第一次自动查询
          pagerOpen: true,
        },
        url: '',
        buttonList: [], //按钮列表
        srcArr: [],
        getTreeData: [],
        ROLE_ID: '',
        postTreeData: [],
        unsubs: [],
        oldJson: {},
        defaultExpandedKeys: [],
        padTreeData: [],
        padCheckData: [],
        padPostTreeData: [],
        padChange: false,
        pcChange: false,
        setCheckedList: [],
        initialList: [],
        isCheckout: false,
        roleJson: [],
        firstPcLevel: [],
        firstPdaLevel: [],
        formData: {},
        userTablesColumn: [
          { label: translateTitle('Dams.ApplicationInterface.用户名称'), porp: 'USER_NAME' },
          { label: translateTitle('Dams.ApplicationInterface.登录账号'), porp: 'USER_ID' },
        ],
        tabsShow: false,
        firstIndex: 0,
        userDialog: false,
        dialogActiveName: 'first',
        dialogType: '',
        uploadModal: false,
        addDialog: false,
        downloadModal: false,
        subSystem: 'WMS',
        menuTreeDataList: [],
        tabsIndex: 0,
        isCopy: false,
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 149}`
      },
      searchForm() {
        return this.pageSetting[this.moduleName]?.search
      },
      tablesColumn() {
        if (this.pageSetting[this.moduleName]?.dialog) {
          let arr = this.pageSetting[this.moduleName].dialog.form.field
          let newArr = []
          arr.forEach((v) => {
            if (v.type != 'button' && v.type != 'line' && !v.tableHidden) {
              newArr.push({
                label: v.label,
                porp: v.name,
                type: v.type,
              })
            }
          })
          return newArr
        } else {
          return []
        }
      },
    },
    unmounted() {
      this.unsubs.forEach((v) => {
        this.$unsub(v)
      })
    },
    created() {
      let systemOptions = cloneDeep(this.$store.getters['user/apps'])
      let index = systemOptions.findIndex((el) => el.APP_CODE == 'DAMS')
      if (index > -1) {
        systemOptions.splice(index, 1)
      }
      let index1 = systemOptions.findIndex((el) => el.APP_CODE == 'BQMS')
      if (index1 > -1) {
        systemOptions.splice(index1, 1)
      }
      this.subSystem = systemOptions[0].APP_CODE
      this.init()
    },
    methods: {
      translateTitle,
      // 全部展开
      unFoldAll2(data) {
        let self = this
        data.forEach((el) => {
          self.$refs[`tree_menu_${this.menuTreeDataList[this.tabsIndex].name}`][0].store.nodesMap[el.id].expanded = true
          el.children && el.children.length > 0 ? self.unFoldAll2(el.children) : '' // 子级递归
        })
      },
      // 全部折叠
      collapseAll2(data) {
        let self = this
        data.forEach((el) => {
          self.$refs[`tree_menu_${this.menuTreeDataList[this.tabsIndex].name}`][0].store.nodesMap[el.id].expanded = false
          el.children && el.children.length > 0 ? self.collapseAll2(el.children) : '' // 子级递归
        })
      },
      selectChange(val) {
        this.subSystem = val
        this.tabsShow = false
        this.menuTreeDataList = []
        this.buttonList = []
        this.tabsIndex = 0
        this.onSubmit([{}])
      },
      async getUserList() {
        this.notAssociatedTables = []
        let url = GFCD('dams')
        let res = await getList(`${url.domain}${url.baseUrl}`, {
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999, APP_CODE: this.subSystem }),
          method: 'sysUserServiceImpl.queryAllUserInfos',
        })
        getList(this.url, {
          method: this.pageSetting[this.moduleName].queryUser, //查询按钮
          data: JSON.stringify({
            '#LIMIT#': '1',
            '#PAGE_SIZE#': 999,
            ROLE_ID: this.ROLE_ID,
            APP_CODE: this.subSystem,
          }),
        }).then((r) => {
          console.log(r)
          this.associatedTables = r.data.map((el) => el.USER_ID)
          this.notAssociatedTables = res.data
        })
      },
      roleBindUserSave() {
        this.$nextTick(() => {
          let checkboxList = this.associatedTables
          let submitList = []
          checkboxList.forEach((row) => {
            submitList.push({
              USER_ID: row,
              USER_ROLE_ID: this.ROLE_ID,
            })
          })
          let submitFrom = {
            USER_ROLE_ID: this.ROLE_ID,
            APP_CODE: this.subSystem,
            USER_ROLE: submitList,
          }
          getList(this.url, {
            method: this.pageSetting[this.moduleName].saveUserRole,
            data: JSON.stringify(submitFrom),
          }).then((res) => {
            if (res.code == '00000') {
              this.$message({
                message: res.msg,
                type: 'success',
              })
              this.treeShowData()
              this.getUserList()
            }
          })
        })
      },
      clickOne(item) {
        console.log(item)
        let _this = this
        let curTime = new Date().getTime()
        let lastTime = _this.lastTapDiffTime
        _this.lastTapDiffTime = curTime
        //两次点击间隔小于300ms, 认为是双击
        let diff = curTime - lastTime
        if (diff < 300) {
          this.ROLE_ID = item.ROLE_ID
          this.buttonList = []
          this.treeShowData()
        } else {
          // 单击事件延时300毫秒执行
          return false
        }
      },
      editClick(item) {
        this.addDialog = true
        this.isEditor = true
        this.dialogType = 'modify'
        this.formDialog = item
      },
      roleCopy(item) {
        console.log(item)
        // if (this.checkboxList.length == 0) return this.$message({ message: '请选择数据后再进行复制', type: 'error' })
        // if (this.checkboxList.length > 1) return this.$message({ message: '只能选择一项数据进行复制', type: 'error' })
        let form = cloneDeep(item)
        delete form._X_ID
        delete form.ORG_ID
        delete form['#SEQ#']
        let emptyKeyList = ['ROLE_ID', 'ADDTIME', 'ADDWHO', 'EDITTIME', 'EDITWHO']
        for (const key in form) {
          emptyKeyList.forEach((row) => {
            if (key == row) form[row] = ''
          })
        }
        this.isCopy = true
        form.OLD_ROLE_ID = item.ROLE_ID
        this.addDialog = true
        this.isEditor = false
        this.dialogType = 'add'
        this.formDialog = form
      },
      toLead() {
        this.uploadModal = true
      },
      downloadClose(row) {
        this.downloadModal = row
      },
      closeUpload() {
        this.uploadModal = false
        // this.formData = {
        //   CREATE_TIME: [],
        // }
        // this.tables.limit = 1
        this.onSubmit([{}])
      },
      newAdd() {
        this.addDialog = true
        this.isEditor = false
        this.dialogType = 'add'
        let arr = this.pageSetting[this.moduleName]?.dialog.form.field
        arr.forEach((v) => {
          // if (!v.hidden) {
          // 下拉选
          if (v.type == 'select') {
            this.formDialog[v.name] = ''
            if (v.isFixed) {
              this.formDialog[v.name] = v.options[0].CODE
              return
            }
            if (v.value) {
              this.formDialog[v.name] = v.value
              return
            }
          }
          // input和textarea
          else if (v.type == 'input' || v.type == 'textarea') {
            if (!!v.value != false) {
              // 有默认值渲染
              this.formDialog[v.name] = v.value
            } else {
              // 没有默认值渲染空
              this.formDialog[v.name] = null
            }
          } else if (v.type == 'imgUpload') {
            this.formDialog[v.name] = ''
          } else if (v.type == 'radio') {
            this.formDialog[v.name] = v.value ? v.value : ''
          } else if (v.type == 'dateTime') {
            this.formDialog[v.name] = v.value ? v.value : null
          } else if (v.type == 'switch') {
            this.formDialog[v.name] = v.value ? v.value : null
          } else if (v.type == 'numInput') {
            this.formDialog[v.name] = v.value ? v.value : 0
          }
          // }
        })
        if (this.name == 'UserList') {
          this.formDialog.TYPE = 'add'
        }
        delete this.formDialog.ID
        delete this.formDialog.ORG_ID
        console.log(this.formDialog)
      },
      dialogClick() {
        this.getUserList()
      },
      roleUserBind() {
        this.userDialog = true
        this.getUserList()
      },
      firstTab(e) {
        this.firstIndex = e.index
        this.treeShowData()
      },
      backTab() {
        this.tabsShow = false
      },
      nodePcClick(node) {
        // console.log(node)
        // const pidList = ['100', 'wcs100', 'lpms100', 'les100', 'lwms100']
        if (!node.pid || this.activeName == 'PDA' || node.JUMP == 'N') return
        this.getJson(node.id)
      },
      checkedChange(nodes, data) {
        let obj = {
          multiples: data.checkedNodes,
          keys: data.checkedKeys,
        }
        let _arr = []
        obj['multiples'].forEach((v) => {
          _arr.push(v.id, v.pid)
        })
        this.menuTreeDataList[this.tabsIndex].checkList = [...new Set(_arr.filter(Boolean))]
      },
      getDefault(treeData, list) {
        console.log('getDefault', treeData, list)
        let _arr = []
        function getArr(tree, list) {
          for (let index = 0; index < tree.length; index++) {
            const element = tree[index]
            if (element?.children?.length > 0) {
              getArr(element.children, list)
            }
            if (list.find((el) => el == element.id) && (!element.children || element?.children?.length == 0)) {
              _arr.push(element.id)
            }
          }
        }
        if (treeData && treeData.children) getArr(treeData.children, list)
        return _arr
      },
      checkChange(data, obj) {
        console.log(data, obj)
        this.isCheckout = true
        // this.setCheckedList = this.$refs[`tree_btn_${this.menuTreeDataList[this.tabsIndex].name}`].getCheckedKeys()
        // if (obj.halfCheckedKeys.length > 0) {
        //   obj.halfCheckedKeys.forEach((item) => {
        //     this.setCheckedList.push(item)
        //   })
        // }
        const list = this.setLowerLevelCheck(this.buttonList[0], data._id, false) //获取点击节点及子节点
        const list1 = this.setLowerLevelCheck(list[0], data._id, true) //转为一维id数组
        if (obj.checkedKeys.find((el) => el === data._id)) {
          //勾选
          list1.forEach((r) => {
            this.setCheckedList.push(r)
          })
        } else {
          //取消勾选
          this.setCheckedList = this.removeElements(obj.checkedKeys, list1)
        }
        this.$refs[`tree_btn_${this.menuTreeDataList[this.tabsIndex].name}`].setCheckedKeys(this.setCheckedList, true)
      },
      removeElements(A, B) {
        return A.filter((itemA) => {
          return !B.some((itemB) => {
            return JSON.stringify(itemA) === JSON.stringify(itemB)
          })
        })
      },
      setLowerLevelCheck(tree, id, open) {
        const result = []
        function search(node) {
          if (open === true) {
            result.push(node._id)
          } else {
            if (node._id === id) {
              result.push(node)
            }
          }
          if (node.children && node.children.length > 0) {
            for (const child of node.children) {
              search(child)
            }
          }
        }
        search(tree)
        console.log('result====', result)
        return result
      },
      handleClick(e) {
        this.tabsIndex = e.index
        this.buttonList = []
      },
      common_event(event_name, type) {
        this[event_name](type)
      },
      save(type) {
        if (type == 'main') {
          let postObj = []
          console.log(this.menuTreeDataList)
          this.menuTreeDataList.forEach((row) => {
            if (row.checkList && row.checkList.length > 0) {
              row.checkList.forEach((r) => {
                postObj.push({
                  MENU_CODE: r,
                  ROLE_ID: this.ROLE_ID,
                  APP_CODE: this.subSystem,
                })
              })
            }
            // let arr = { ROLE_ID: '2', APP_CODE: '121', MENU_CODE: ['21', '343'] }
            if (!row.checkList || row.checkList.length == 0) {
              let list = row.firstPcLevel.concat(row.secondListPC)
              console.log(list)
              list.forEach((r) => {
                postObj.push({
                  MENU_CODE: r,
                  ROLE_ID: this.ROLE_ID,
                  APP_CODE: this.subSystem,
                })
              })
            }
          })
          console.log(postObj)
          this.loadingTree = true
          this.saveFuc(postObj, this.pageSetting[this.moduleName].saveRolePage)
        } else if (type == 'chirden') {
          let subObj
          if (this.isCheckout) {
            subObj = this.setCheckedList
          } else {
            subObj = this.roleJson
          }
          this.saveFuc(
            {
              ROLE_PAGE_JSON: subObj.length == 0 ? null : JSON.stringify(subObj),
              MENU_CODE: this.MENU_CODE,
              ROLE_ID: this.ROLE_ID,
              APP_CODE: this.subSystem,
            },
            this.pageSetting[this.moduleName].savePageJson
          )
        }
      },
      // 保存接口
      saveFuc(dataInfo, method) {
        getList(this.url, {
          method: method, //查询按钮
          data: JSON.stringify(dataInfo),
        }).then((res) => {
          if (res.code == '00000') {
            this.$baseMessage(res.msg, 'success')
            if (method == this.pageSetting[this.moduleName].saveRolePage) {
              this.loadingTree = false
              this.pcChange = false
              this.padChange = false
              this.query(
                { ROLE_ID: this.ROLE_ID, '#LIMIT#': 1, '#PAGE_SIZE#': 9999, SUB_SYSTEM: this.subSystem, APP_CODE: this.subSystem },
                this.pageSetting[this.moduleName].getMenuRoleMethod
              )
            } else if (method == this.pageSetting[this.moduleName].savePageJson) {
              this.loadingCheckbox = false
              this.initialList = []
              this.isCheckout = false
              this.getJson(this.MENU_CODE)
            }
          }
        })
      },
      windowResize: debounce(function () {
        console.log('document.documentElement.clientHeight', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      init() {
        this.configSetting = GFCD('dams')
        this.url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        this.windowResize()
        this.eventInit()
        this.uploadOptions.url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        this.onSubmit([])
      },
      async onSubmit(p) {
        let sub = JSON.parse(JSON.stringify(p))
        let obj = {}
        obj = {
          '#LIMIT#': this.tables.limit,
          '#PAGE_SIZE#': this.tables.pageSize,
          APP_CODE: this.subSystem,
          ...sub[0],
        }
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        console.log(this.pageSetting)
        if (this.pageSetting[this.moduleName]?.search) {
          let res = await getList(url, {
            data: JSON.stringify(obj),
            method: this.pageSetting[this.moduleName].search.form.method,
          })
          this.tables.tableList = res.data
          this.tables.count = res.count
          // for (let index = 0; index < 30; index++) {
          //   this.tables.tableList.push({ ROLE_NAME: 'wms系统管理员（勿删）' })
          // }
          // this.tables.tableList.push({ ROLE_NAME: 'wms系统管理员（勿删）' })
        }
      },
      treeShowData() {
        if (this.firstIndex == 0) {
          this.loadingTree = true
          // 主权限
          this.treeData = []
          this.padTreeData = []
          this.query(
            { ROLE_ID: this.ROLE_ID, '#LIMIT#': 1, '#PAGE_SIZE#': 9999, SUB_SYSTEM: this.subSystem, APP_CODE: this.subSystem },
            this.pageSetting[this.moduleName].getMenuRoleMethod
          )
        } else {
          getList(this.url, {
            method: this.pageSetting[this.moduleName].queryUser, //查询按钮
            data: JSON.stringify({
              '#LIMIT#': '1',
              '#PAGE_SIZE#': 999,
              ROLE_ID: this.ROLE_ID,
              APP_CODE: this.subSystem,
            }),
          }).then((res) => {
            console.log(res)
            this.userTables.tableList = res.data
            this.userTables.count = res.count
          })
        }
      },
      dialogFuc(method) {
        let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        let subForm = JSON.parse(JSON.stringify({ APP_CODE: this.subSystem, ...this.formDialog }))
        if (this.isCopy) {
          subForm.NEW_ROLE_ID = subForm.ROLE_ID
        }
        getList(url, {
          method: method,
          data: JSON.stringify(subForm),
        }).then((res) => {
          if (res.code == '00000') {
            this.$baseMessage(res.msg, 'success')
            this.isCopy = false
            this.addDialog = false
            this.onSubmit(this.subForm)
          }
        })
      },
      deleteRole(obj) {
        this.$confirm(translateTitle('Dams.ApplicationInterface.确定删除'), translateTitle('Dams.ApplicationInterface.提示'), {
          confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
          cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
          type: 'warning',
        })
          .then(async () => {
            let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
            let subObj = { ROLE_ID: obj.ROLE_ID, ACTION: 'DELETE', LANGUAGE: 'zh_CN', OUT_RETURN_CODE: '', APP_CODE: this.subSystem }
            await getList(url, {
              data: JSON.stringify(subObj),
              method: this.pageSetting[this.moduleName].deleteMethod,
            })
            this.$message({
              type: 'success',
              message: translateTitle('Dams.ApplicationInterface.删除成功') + `!`,
            })
            this.onSubmit(this.subForm)
          })
          .catch((e) => {
            console.log(e)
          })
      },
      async getJson(id) {
        this.defaultExpandedKeys = []
        this.buttonList = []
        let res = await getList(this.url, {
          method: this.pageSetting[this.moduleName].getJsonMethod, //查询按钮
          data: JSON.stringify({ ROLE_ID: this.ROLE_ID, MENU_CODE: id, '#LIMIT#': 1, '#PAGE_SIZE#': 9999, APP_CODE: this.subSystem }),
        })
        if (res.data.length == 0 || !res.data[0].PAGE_JSON) return (this.buttonList = [])
        let pageJson = ungzip(res.data[0].PAGE_JSON)
        console.log(pageJson)
        this.oldJson = res.data.length > 0 ? pageJson : []
        this.roleJson = res.data.length > 0 && res.data[0].ROLE_PAGE_JSON ? JSON.parse(res.data[0].ROLE_PAGE_JSON) : []
        this.loadingCheckbox = false
        this.buttonList = getComponents(this.oldJson, [
          'uiButton',
          'uiTable',
          'uiUpload',
          'uiDownload',
          'uiTolead',
          'uiTabs',
          'tabsList',
          'uiDropdown',
        ])
        console.log(this.buttonList, this.roleJson)
        // this.defaultExpandedKeys = this.getDefault(this.buttonList[0], this.roleJson)
        this.defaultExpandedKeys = this.roleJson
        this.MENU_CODE = id
      },
      getTreeFormat(list) {
        let secondListPC = []
        let firstPcLevel = []
        let _arr = []
        list.forEach((row) => {
          if (row.IS_CHECKED == 'Y') {
            if (row.MENU_LV == 2) {
              //第二级
              secondListPC.push(row.ID)
            }
          }
          _arr.push({
            id: row.ID,
            name: row.MENU_NAME,
            pid: row.PID,
            children: [],
            label: row.MENU_NAME,
            IS_CHECKED: row.IS_CHECKED,
            JUMP: row.JUMP,
            MENU_LV: row.MENU_LV,
          })
        })
        let treeList = arrayToTree(_arr, 'id', 'pid', 'children')
        treeList.forEach((row) => {
          //如果一级菜单没有二级菜单，需要默认勾选
          if (row.IS_CHECKED == 'Y' && row.children.length > 0) {
            firstPcLevel.push(row.id)
          }
          if (row.IS_CHECKED == 'Y' && row.children.length == 0) {
            secondListPC.push(row.id)
          }
        })
        return { treeDataList: treeList, firstPcLevel, secondListPC }
      },
      // 查询接口
      query(dataInfo, method) {
        getList(this.url, {
          method: method, //查询按钮
          data: JSON.stringify(dataInfo),
        }).then((res) => {
          console.log('res', res)
          this.menuTreeDataList = []
          this.loadingTree = false
          for (const key in res.data) {
            const element = res.data[key]
            this.menuTreeDataList.push({ name: key, ...this.getTreeFormat(element) })
            this.$nextTick(() => {
              console.log(this.$refs[`tree_menu_${key}`])
              this.$refs[`tree_menu_${key}`].setCheckedKeys(this.getTreeFormat(element).secondListPC)
            })
          }
          // this.activeName = this.tabsList[0].name
          console.log(this.menuTreeDataList)
        })
      },
      eventInit() {
        this.$sub(`MenuButtonPulic_forms_on_dialog`, (page_arr) => {
          console.log(page_arr, this.dialogType, this.isCopy)
          if (this.isCopy) {
            this.dialogFuc('roleServiceImpl.copyRole')
          } else {
            if (this.dialogType == 'add') {
              this.dialogFuc(this.pageSetting[this.moduleName].addMethod)
            } else if (this.dialogType == 'modify') {
              // 修改模态框
              this.dialogFuc(this.pageSetting[this.moduleName].updateMethod)
            }
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  // @import '@/ve/styles/elements.scss';
  .role-heder {
    display: flex;
    justify-content: space-between;
    padding: 10px 1rem;
    font-weight: 600;
    color: #333333;
  }
  .role-content {
    overflow-y: auto;
    height: calc(100% - 38px);
  }
  .role-item {
    padding: 10px 1.5rem;
    border-bottom: 1px solid #eaeef5;
    display: flex;
    justify-content: space-between;
    color: #666666;
    font-size: 12px;
    .role-item-btn {
      display: none;
    }
    &:hover .role-item-btn {
      display: block;
      width: 70px;
      display: flex;
      justify-content: space-around;
    }
    &:hover {
      background-color: #f4f8fe;
    }
  }
  :deep() {
    .el-transfer__button {
      display: block;
      margin: 0;
    }
    .el-transfer__button:nth-child(2) {
      margin-top: 10px;
    }
    .el-tabs__item {
      font-size: 12px;
      height: 24px;
      line-height: 24px;
    }
    .el-dialog__body {
      .el-form--inline .el-form-item {
        width: 23%;
        display: inline-block;
        // margin-bottom: 0;
      }
      .el-form-item__label {
        display: block;
        text-align: left;
        line-height: 24px;
        font-size: 12px;
      }
      .el-form-item__content {
        width: 100%;
      }
      // .el-select {
      //   width: 100%;
      // }
      .item_button {
        display: block !important;
        width: 100% !important;
        text-align: center;
      }
    }
  }
</style>
